package com.springcloud.sc.ucpv5.client.application.util;

import java.io.File;
import java.io.FilenameFilter;
import java.util.Arrays;
import java.util.Comparator;

import com.springcloud.sc.ucpv5.client.util.PublicUtil;

public class LogFileCleaner {
	private int totalNum = 1000;
	private String fileNameStart = "";
	private int curFileNum;
	private static File logDir;

	public LogFileCleaner(String fileNameStart, int maxNum) {
		super();
		if (logDir == null) {
			String prefix = PublicUtil.nullToEmpty(FrameworkUtil.getAbsolutePath(Constant.TRACE_DIRECTORY_PATH));
			if ("".equals(prefix)) {
				prefix = "log" + Constant.FILE_SEPARATOR;
			}

			logDir = new File(prefix);
		}
		this.totalNum = maxNum;
		this.logDir = logDir;
		this.fileNameStart = fileNameStart;

		if (logDir.exists()) {
			curFileNum = getFileList().length;
			if (curFileNum >= totalNum) {
				clearLogFile();
			}
		}
	}

	private void clearLogFile() {
		File[] files = getFileList();
		Arrays.sort(files, new Comparator<File>() {
			public int compare(File o1, File o2) {
				if (o1.lastModified() > o2.lastModified())
					return 1;
				return -1;
			}
		});

		for (int i = 0; i <= totalNum / 2; ++i) {
			try {
				files[i].delete();
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
	}

	private File[] getFileList() {
		File[] ret = logDir.listFiles(new FilenameFilter() {
			public boolean accept(File dir, String name) {
				return name.startsWith(fileNameStart);
			}
		});

		return ret;
	}

	public void filenew() {
		curFileNum++;
		if (curFileNum >= totalNum) {
			curFileNum = 0;
			clearLogFile();
		}
	}
}
